<template>
  <div class="msui-upload">
    <el-upload
      :class="{ disabled: uploadDisabled }"
      ref="ElUpload"
      :action="action"
      :disabled="disabled"
      :before-upload="beforeUpload"
      :list-type="attrs.listType || 'picture-card'"
      :headers="getHeader()"
      :auto-upload="true"
      :multiple="false"
      :limit="attrs.bind.limit || 3"
      :on-exceed="handleExceed"
      :on-success="onsuccess"
      :file-list="fileList"
      :on-remove="remove"
      :on-error="onError"
      v-bind="$attrs"
    >
      <el-button slot="trigger" size="small" type="primary" v-if="attrs.bind?.trigger">
        {{ attrs.bind?.trigger }}
      </el-button>
      <i class="el-icon-folder-add" style="font-size: 30px" v-else></i>
      <div slot="tip" class="el-upload__tip">{{ attrs.bind?.tip }}</div>
      <div slot="file" slot-scope="{ file }">
        <el-image :src="conpute(file[prop.url])" alt="" style="height: 72px; width: 72px" fit="cover">
          <div slot="error" class="image-slot" style="text-align: center; line-height: 72px; font-size: 20px">
            <i class="el-icon-loading"></i>
          </div>
        </el-image>
        <div v-if="attrs.bind.type !=1" class="upload-text">{{ file[prop.name] }}</div>
        <span class="el-upload-list__item-actions" :title="file[prop.name]">
          <span class="el-upload-list__item-preview" @click="preview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <msui-dialog :options="dialogOptions">
      <div style="height: 650px">
        <iframe width="100%" height="100%" :src="attachmentSrc" alt="" />
      </div>
    </msui-dialog>
    <el-image-viewer
      :z-index="10000000000"
      v-if="showViewer"
      :showViewer="showViewer"
      :on-close="onclose"
      :url-list="[image]"
    />
  </div>
</template>
<script>
import axios from 'axios'
import doc from './static/doc.png'
import docx from './static/docx.png'
import ppt from './static/ppt.png'
import rar from './static/rar.png'
import txt from './static/txt.png'
import xls from './static/xls.png'
import xlsx from './static/xlsx.png'
import zip from './static/zip.png'
import pdf from './static/pdf.png'
import mp4 from './static/mp4.png'
import exe from './static/exe.png'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { MessageBox, Message } from 'element-ui'
export default {
  name: 'MsuiUpload',
  components: {
    ElImageViewer
  },
  data() {
    return {
      image: '',
      showViewer: false,
      exe,
      doc,
      docx,
      ppt,
      rar,
      txt,
      xls,
      xlsx,
      zip,
      pdf,
      mp4,
      dialogOptions: {
        bind: {
          title: '文件预览',
          show: false,
          width: '55%',
          showFoot: false,
          appendToBody: true,
          modal: false
        }
      },
      attachmentSrc: '',
      disabled: false,
      dialogVisible: false,
      cloneList: [],
      fileList: [],
      uploadDisabled: false,
      action: process.env.VUE_APP_BASE_API + '/load/upload'
    }
  },
  props: {
    attrs: {
      type: Object,
      default: () => {
        return {}
      }
    },
    value: {
      default: () => {
        return []
      }
    }
  },
  computed: {
    prop() {
      if (this.attrs?.bind?.props) {
        return this.attrs.bind.props
      } else {
        return {
          url: 'url',
          name: 'name'
        }
      }
    }
  },
  mounted() {
    if (this.attrs?.bind?.disabled) {
      this.disabled = true
    }
    if (this.value && typeof this.value == 'string') {
      this.uploadDisabled = true
      let valuelist = this.value.split(',').map((item) => {
        return {
          url: item,
          name: item
        }
      })
      this.fileList = valuelist
      if (this.attrs?.bind?.limit > valuelist.length) {
        this.uploadDisabled = false
      } else {
        this.uploadDisabled = true
      }
    } else if (this.value && this.value instanceof Array) {
      this.fileList = this.value
      this.uploadDisabled = false
    } else {
      this.fileList = []
      this.uploadDisabled = false
    }
  },
  watch: {
    value: {
      handler() {
        if (this.value && typeof this.value == 'string') {
          this.uploadDisabled = true
          let valuelist = this.value.split(',').map((item) => {
            return {
              url: item,
              name: item
            }
          })
          this.fileList = valuelist
        } else if (this.value && this.value instanceof Array) {
          this.fileList = this.value
        } else {
          this.fileList = []
        }
        if (this.attrs?.bind?.limit > this.fileList.length) {
          this.uploadDisabled = false
        } else {
          this.uploadDisabled = true
        }
      },
      deep: true
    }
  },
  methods: {
    onclose() {
      this.showViewer = false
    },
    conpute(url) {
      if (!url) return
      let list = url.split('.')
      let length = list.length - 1
      let type = list[length]
      if (this[type]) {
        return this[type]
      } else {
        return url
      }
    },
    handleRemove(file) {
      this.$refs.ElUpload.handleRemove(file)
    },
    format(data, type = false) {
      if (!data) return
      let list = data.split('.')
      if (type) {
        return list[list.length - 1]
      }
      return this[list[list.length - 1]]
    },
    preview(val) {
      if ('jpg,png,jpeg'.indexOf(this.format(val[this.prop.url], true)) >= 0) {
        this.image = val[this.prop.url]
        this.showViewer = true
        return
      }
      this.dialogOptions.bind.show = true
      this.attachment = val[this.prop.url]
      this.previewFile(this.attachment)
    },
    previewFile(attachment) {
      // 根据文件格式显示预览内容
      const fileExtension = attachment.split('.').pop().toLowerCase()
      if (fileExtension === 'xlsx' || fileExtension === 'docx') {
        this.attachmentSrc = 'https://view.officeapps.live.com/op/view.aspx?src=' + attachment
      } else {
        this.attachmentSrc = attachment
      }
    },
    handleDownload(file) {
      debugger
      return axios({
        baseURL: process.env.VUE_APP_BASE_API,
        url: '/load/download',
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        },
        params: {
          fileUrl: file[this.prop.url],
          source: 2
        },
        responseType: 'blob',
        transformResponse: [
          (data) => {
            const href = window.URL.createObjectURL(data)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = href
            link.download = decodeURIComponent(file[this.prop.name])
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(link)
          }
        ]
      }).finally(() => {})
    },
    onError() {
      this.disabled = false
    },
    beforeUpload() {
      this.disabled = true
      return true
    },
    remove(file, fileList) {
      if (!this.attrs.bind?.props) {
        let files = fileList.map((item) => item.url).join(',')
        this.$emit('input', files)
      }
      if (this.attrs.bind.onSuccess) {
        this.attrs.bind.onSuccess(null, file, fileList)
      }
    },
    onsuccess(response, file, fileList) {
      if (process.env.VUE_APP_CODE == 32) {
        Message({
          message: '此平台为非涉密平台请勿上传涉密文件',
          type: 'info'
        })
      }
      this.disabled = false
      let files = fileList
        .map((item) => {
          if (item.response) {
            return item.response.data.url
          } else {
            return item.url
          }
        })
        .join(',')
      this.$nextTick(() => {
        if (this.attrs?.bind?.limit > this.fileList.length) {
          this.uploadDisabled = false
        } else {
          this.uploadDisabled = true
        }
      })
      if (!this.attrs.bind?.props) {
        this.$emit('input', files)
      }
      if (this.attrs.bind.onSuccess) {
        this.attrs.bind.onSuccess(response, file, fileList)
      }
    },
    getHeader() {
      return {
        Authorization: localStorage.getItem('token')
      }
    },
    request() {
      return true
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制上传 ${this.attrs?.bind?.limit || 3} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>
<style>
.msui-upload .el-upload-list__item {
  transition: none !important;
}

el-upload-list
  el-upload-list--picture-card
  is-disabled
  .msui-upload
  .el-upload-list--picture-card
  .el-upload-list__item-actions {
  transition: none !important;
}

.disabled .el-upload--picture-card {
  display: none;
}

.msui-upload .is-disabled + div {
  cursor: not-allowed;
  display: none;
}

.is-disabled .el-upload-list__item-delete {
  display: none !important;
}

.msui-upload .is-disabled + div.el-upload--picture-card:hover {
  border-color: #e4e7ed;
}

.el-upload-list--picture-card .el-upload-list__item-actions {
  font-size: 16px;
}

.upload-text {
  position: absolute;
  left: 90px;
  top: 0;
  width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 90px;
}
</style>
